﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.UI;
using JTTMS.App.$TableNames.Dto;
using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using Abp.Linq.Extensions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JTTMS.THEntity.$TableNames;
using Microsoft.EntityFrameworkCore;
using JTTMS.THEntity.Drivers;
using Abp.AutoMapper;

namespace JTTMS.App.$TableNames
{
    /// <summary>
    /// $CNName
    /// </summary>
    public class $TableNameAppService : ApplicationService<$TableName, $TableNameOutput, int, $TableNameSearchInput, $TableNameCreateInput, $TableNameEditInput, EntityDto>, I$TableNameAppService
    {
        private readonly IRepository<$TableName> _$tableNameRepository;

        public $TableNameAppService(IRepository<$TableName> repository) : base(repository)
        {
            _$tableNameRepository = repository;
        }

        /// <summary>
        /// 根据ID查询$CNName
        /// </summary>
        /// <param name="id"></param>
        protected override Task<$TableName> GetEntityByIdAsync(int id)
        {
            return _$tableNameRepository.FirstOrDefaultAsync(a => a.Id == id);
        }

        /// <summary>
        /// $CNName列表过滤
        /// </summary>
        /// <param name="input"></param>
        protected override IQueryable<$TableName> CreateFilteredQuery($TableNameSearchInput input)
        {
            return base.CreateFilteredQuery(input).OrderBy(input.Sorting);
                //.WhereIf(!string.IsNullOrWhiteSpace(input.name), r => r.name.Contains(input.name));
        }

        /// <summary>
        /// 新建$CNName
        /// </summary>
        /// /// <param name="input"></param>
        public override async Task<$TableNameOutput> CreateAsync($TableNameCreateInput input)
        {
            CheckCreatePermission();
            var data = ObjectMapper.Map<$TableName > (input);  
            data.TenantId = 1;//暂时默认值
            await _$tableNameRepository.InsertAsync(data);
            await UnitOfWorkManager.Current.SaveChangesAsync();
            return ObjectMapper.Map<$TableNameOutput > (data);
        }

        /// <summary>
        /// 更新$CNName
        /// </summary>
        /// <param name="input"></param>
        public override async Task<$TableNameOutput> UpdateAsync($TableNameEditInput input)
        {
            var $tableNameEntity = await _$tableNameRepository.FirstOrDefaultAsync(x => input.Id == x.Id);
            $tableNameEntity.TenantId = 1;//暂时默认值
            ObjectMapper.Map(input, $tableNameEntity);
            await _$tableNameRepository.UpdateAsync($tableNameEntity);
            await UnitOfWorkManager.Current.SaveChangesAsync();
            return ObjectMapper.Map<$TableNameOutput > ($tableNameEntity);
        }


    }
}
